﻿using Microsoft.AspNetCore.Mvc.Filters;
using KongMing.Project.Entity.Common;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using KongMing.Project.Common;

namespace KongMing.Project.Common.Filter
{
    /// <summary>
    /// 自定义全局异常处理过滤器
    /// </summary>
    public class GlobalExceptionFilter : IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                BaseApiResult result = BaseApiResult.Error(context.Exception.Message);
                if (context.Exception is BusinessException exp)
                {
                    result.code = (int)exp.ErrorCode;
                }
                // 定义返回类型
                context.Result = new ContentResult
                {
                    // 返回状态码设置为200，表示成功
                    StatusCode = StatusCodes.Status200OK,
                    // 设置返回格式
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(result)
                };
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
